<template>
  <el-dialog
    v-model="dialogVisible"
    title="用户角色分配"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="mb-4">
      <p class="text-sm text-gray-600 mb-2">用户：{{ userData?.username }} ({{ userData?.realName }})</p>
    </div>
    
    <div class="mb-4">
      <el-checkbox-group v-model="selectedRoleCodes" class="flex flex-wrap gap-2">
        <el-checkbox
          v-for="role in roleList"
          :key="role.code"
          :label="role.code"
          class="mr-2 mb-2"
        >
          {{ role.name }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { getAllRoles, getUserRoles, assignRolesToUser } from "@/api/role";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  userData: {
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["update:modelValue", "success"]);

const loading = ref(false);
const roleList = ref([]);
const selectedRoleCodes = ref([]);

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

// 加载所有角色
const loadAllRoles = async () => {
  try {
    const data = await getAllRoles();
    roleList.value = data || [];
  } catch (error) {
    ElMessage.error("获取角色列表失败");
  }
};

// 加载用户当前角色
const loadUserRoles = async () => {
  if (!props.userData) return;

  try {
    const data = await getUserRoles(props.userData.id);
    selectedRoleCodes.value = data.map(role => role.code);
  } catch (error) {
    ElMessage.error("获取用户角色失败");
  }
};

const handleClose = () => {
  dialogVisible.value = false;
  selectedRoleCodes.value = [];
};

const handleSubmit = async () => {
  if (!props.userData) return;

  try {
    loading.value = true;
    // 过滤掉null、undefined和空字符串的角色编码
    const validRoleCodes = selectedRoleCodes.value.filter(code => code && code.trim() !== '');
    await assignRolesToUser(props.userData.id, validRoleCodes);
    ElMessage.success("角色分配成功");
    emit("success");
    handleClose();
  } catch (error) {
    ElMessage.error("角色分配失败");
  } finally {
    loading.value = false;
  }
};

// 监听对话框打开
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      loadAllRoles();
      loadUserRoles();
    }
  }
);
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>